#include "stdafx.h"
#include "PboReadPixels.h"


PboReadPixels::PboReadPixels()
{
	m_pboIds[0] = m_pboIds[1] = 0;
	m_bmp = nullptr;
	m_currPbo = 0;
}


PboReadPixels::~PboReadPixels()
{
	if (m_bmp)
	{
		FreeImage_Unload(m_bmp);
		m_bmp = nullptr;
	}
	glDeleteBuffers(2, m_pboIds);
}

void PboReadPixels::Init(int width, int height, int bpp)
{
	m_width = width;
	m_height = height;
	m_pixelFormat = bpp == 24 ? GL_BGR : GL_BGRA;
	m_dataSize = m_width * m_height * bpp/8;
	glGenBuffers(2, m_pboIds);
	glBindBuffer(GL_PIXEL_PACK_BUFFER, m_pboIds[0]);
	glBufferData(GL_PIXEL_PACK_BUFFER, m_dataSize, 0, GL_STREAM_READ);
	glBindBuffer(GL_PIXEL_PACK_BUFFER, m_pboIds[1]);
	glBufferData(GL_PIXEL_PACK_BUFFER, m_dataSize, 0, GL_STREAM_READ);

	glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
	m_bmp = FreeImage_Allocate(m_width, m_height, bpp);
	m_data = FreeImage_GetBits(m_bmp);
}

void PboReadPixels::Read(int x, int y)
{
	glBindBuffer(GL_PIXEL_PACK_BUFFER, m_pboIds[m_currPbo]);
	glReadPixels(x, y, m_width, m_height, m_pixelFormat, GL_UNSIGNED_BYTE, 0);

	m_currPbo = 1 & ~m_currPbo;
	// map the PBO that contain framebuffer pixels before processing it
	//glBindBuffer(GL_PIXEL_PACK_BUFFER, m_pboIds[m_currPbo]);
	glGetNamedBufferSubData(m_pboIds[m_currPbo], 0, m_dataSize, m_data);
		char filename[300];
		sprintf(filename, "d:/pboImg/%d.jpg", m_bmpIndex++);
		bool fok = FreeImage_Save(FIF_JPEG, m_bmp, filename);
	//GLubyte* src = (GLubyte*)glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY);
	//if (src)
	//{
	//	memcpy(m_data, src, m_dataSize);
	//	
	//	glUnmapBuffer(GL_PIXEL_PACK_BUFFER);     // release pointer to the mapped buffer
	//}
	glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
}